<template>
    <div class="app-container">
        <!-- 查询区域 -->
        <el-card class="search-card">
            <el-form :model="queryParams">
                <el-row :gutter="20">
                    <el-col :span="6">
                        <el-form-item label="站点名称">
                            <el-input v-model="queryParams.siteName" placeholder="请输入站点名称" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="站点状态">
                            <el-select v-model="queryParams.siteStatus" placeholder="请选择站点状态" clearable>
                                <el-option v-for="item in siteStatusOptions" :key="item.dictValue"
                                    :label="item.dictLabel" :value="item.dictValue" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="所属水厂">
                            <el-select v-model="queryParams.siteId" placeholder="请选择所属水厂" clearable>
                                <el-option v-for="item in factoryOptions" :key="item.dictValue" :label="item.dictLabel"
                                    :value="item.dictValue" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6" style="text-align: left;">
                        <el-button type="primary" @click="handleQuery">查询</el-button>
                        <el-button @click="resetQuery">重置</el-button>
                    </el-col>
                </el-row>
            </el-form>
        </el-card>

        <!-- 数据表格区域 -->
        <el-card class="mt-1">
            <el-button type="primary" @click="handleAdd">
                <el-icon>
                    <Plus />
                </el-icon>
                新增站点
            </el-button>
            <el-table :data="siteList" border class="mt-2" v-loading="loading"
                @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" align="center" />
                <el-table-column prop="siteName" label="站点名称" align="center" />
                <el-table-column prop="siteCode" label="站点编号" align="center" />
                <el-table-column prop="siteStatus" label="站点状态" align="center">
                    <template #default="{ row }">
                        <el-tag>{{ getName(siteStatusOptions, row.siteStatus, 'dictValue', 'dictLabel') }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="regionId" label="所属区域" align="center">
                    <template #default="{ row }">
                        <el-tag>{{ getName(regionOptions, row.regionId, 'id', 'name') }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="站点类型" align="center">
                    <template #default="{ row }">
                        <el-tag>
                            {{ getName(siteTypeOptions, row.siteType, 'id', 'name')  }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="siteAddress" label="站点地址" align="center" />
                <el-table-column prop="contactPerson" label="联系人" align="center" />
                <el-table-column prop="contactPhone" label="联系电话" align="center" />

                <el-table-column label="操作" width="280" align="center">
                    <template #default="{ row }">
                        <el-button size="small" @click="handleView(row)">查看</el-button>
                        <el-button size="small" type="primary" @click="handleEdit(row)">编辑</el-button>
                        <el-button size="small" type="warning" @click="showMonitorGroupDialog(row)">监测量</el-button>
                        <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页区域 -->
            <el-pagination class="mt-2" background layout="total, sizes, prev, pager, next, jumper" :total="total"
                v-model:page-size="queryParams.pageSize" v-model:current-page="queryParams.pageNum"
                @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </el-card>

        <!-- 新增/编辑站点对话框 -->
        <el-dialog v-model="dialog.visible" :title="dialog.title" width="800px" :close-on-click-modal="false">
            <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
                <el-form-item label="站点名称" prop="siteName">
                    <el-input v-model="form.siteName" placeholder="请输入站点名称" />
                </el-form-item>
                <el-form-item label="站点编号" prop="siteCode">
                    <el-input v-model="form.siteCode" placeholder="请输入站点编号" />
                </el-form-item>
                <el-form-item label="所属水厂" prop="siteId">
                    <el-select v-model="form.siteId" placeholder="请选择所属水厂" style="width: 100%">
                        <el-option v-for="item in factoryOptions" :key="item.dictValue" :label="item.dictLabel"
                            :value="+item.dictValue" />
                    </el-select>
                </el-form-item>
                <el-form-item label="站点类型" prop="siteStatus">
                    <el-select v-model="form.siteType" placeholder="请选择站点状态" style="width: 100%">
                        <el-option v-for="item in siteTypeOptions" :key="item.id" :label="item.name"
                            :value="item.id + ''" />
                    </el-select>
                </el-form-item>
                <el-form-item label="站点状态" prop="siteStatus">
                    <el-select v-model="form.siteStatus" placeholder="请选择站点状态" style="width: 100%">
                        <el-option v-for="item in siteStatusOptions" :key="item.dictValue" :label="item.dictLabel"
                            :value="item.dictValue" />
                    </el-select>
                </el-form-item>
                <el-form-item label="所属区域" prop="regionId">
                    <el-select v-model="form.regionId" placeholder="请选择所属区域" style="width: 100%">
                        <el-option v-for="item in regionOptions" :key="item.id" :label="item.name" :value="+item.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="站点地址" prop="siteAddress">
                    <el-input v-model="form.siteAddress" placeholder="请输入站点地址" />
                </el-form-item>
               
                <el-form-item label="经纬度">
                    <el-row :gutter="10">
                        <el-col :span="12">
                            <el-input-number v-model="form.latitude" :precision="6" :step="0.000001" placeholder="纬度"
                                style="width: 100%" />
                        </el-col>
                        <el-col :span="12">
                            <el-input-number v-model="form.longitude" :precision="6" :step="0.000001" placeholder="经度"
                                style="width: 100%" />
                        </el-col>
                    </el-row>
                </el-form-item>
                <el-form-item label="联系人" prop="contactPerson">
                    <el-input v-model="form.contactPerson" placeholder="请输入联系人" />
                </el-form-item>
                <el-form-item label="联系电话" prop="contactPhone">
                    <el-input v-model="form.contactPhone" placeholder="请输入联系电话" />
                </el-form-item>
                <el-form-item label="联系邮箱">
                    <el-input v-model="form.contactEmail" placeholder="请输入联系邮箱" />
                </el-form-item>

                <el-form-item label="备注">
                    <el-input v-model="form.remark" type="textarea" :rows="3" placeholder="请输入备注信息" />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="dialog.visible = false">取消</el-button>
                <el-button type="primary" @click="submitForm">保存</el-button>
            </template>
        </el-dialog>

        <!-- 详情对话框 -->
        <el-dialog v-model="detailDialog.visible" :title="`站点详情 - ${detailDialog.data.siteName}`" width="800px">
            <el-descriptions :column="1" border>
                <el-descriptions-item label="站点名称">{{ detailDialog.data.siteName }}</el-descriptions-item>
                <el-descriptions-item label="站点编号">{{ detailDialog.data.siteCode }}</el-descriptions-item>
                <el-descriptions-item label="所属水厂">{{ detailDialog.data.factoryName }}</el-descriptions-item>
                <el-descriptions-item label="站点状态">
                    <el-tag>
                        {{ detailDialog.data.siteType }}
                    </el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="所属区域">{{ detailDialog.data.factoryName }}</el-descriptions-item>
                <el-descriptions-item label="站点地址">{{ detailDialog.data.siteAddress }}</el-descriptions-item>
                <el-descriptions-item label="经纬度">
                    {{ detailDialog.data.latitude }}, {{ detailDialog.data.longitude }}
                </el-descriptions-item>
                <el-descriptions-item label="联系人">{{ detailDialog.data.contactPerson }}</el-descriptions-item>
                <el-descriptions-item label="联系电话">{{ detailDialog.data.contactPhone }}</el-descriptions-item>
                <el-descriptions-item label="联系邮箱">{{ detailDialog.data.contactEmail }}</el-descriptions-item>
                <el-descriptions-item label="站点类型">
                    <el-tag>
                        {{ getStatusLabel(detailDialog.data.siteStatus) }}
                    </el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="创建人">{{ detailDialog.data.creator }}</el-descriptions-item>
                <el-descriptions-item label="创建时间">{{ detailDialog.data.createTime }}</el-descriptions-item>
            </el-descriptions>

            <el-divider content-position="left">设备列表</el-divider>
            <el-table :data="detailDialog.data.deviceList" border>
                <el-table-column prop="deviceId" label="设备编号" align="center" />
                <el-table-column prop="deviceType" label="设备类型" align="center" />
                <el-table-column prop="deviceName" label="设备名称" align="center" />
                <el-table-column label="设备状态" align="center">
                    <template #default="{ row }">
                        <el-tag :type="row.deviceStatus == '1' ? 'success' : 'danger'">
                            {{ row.deviceStatus == '1' ? '正常' : '故障' }}
                        </el-tag>
                    </template>
                </el-table-column>
            </el-table>
            <template #footer>
                <el-button @click="detailDialog.visible = false">关闭</el-button>
            </template>
        </el-dialog>

        <!-- 监测量分组管理对话框 -->
        <el-dialog v-model="monitorGroupDialog.visible" :title="monitorGroupDialog.title" width="1000px" :close-on-click-modal="false">
            <el-tabs v-model="monitorGroupDialog.activeTab">
                <el-tab-pane label="监测量分组" name="group">
                    <div class="toolbar">
                        <el-button type="primary" @click="handleAddGroup">
                            <el-icon><Plus /></el-icon>
                            新增分组
                        </el-button>
                    </div>
                    <el-table :data="monitorGroupList" border class="mt-2" v-loading="groupLoading">
                        <el-table-column prop="groupName" label="分组名称" align="center" />
                        <el-table-column prop="description" label="分组描述" align="center" />
                        <el-table-column label="操作" width="200" align="center">
                            <template #default="{ row }">
                                <el-button size="small" @click="handleEditGroup(row)">编辑</el-button>
                                <el-button size="small" type="danger" @click="handleDeleteGroup(row)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
                
                <el-tab-pane label="监测量列表" name="monitor">
                    <div class="toolbar">
                        <el-button type="primary" @click="handleAddMonitor">
                            <el-icon><Plus /></el-icon>
                            新增监测量
                        </el-button>
                    </div>
                    <el-table :data="monitoringList" border class="mt-2" v-loading="monitorLoading">
                        <el-table-column prop="monitorName" label="监测量名称" align="center" />
                        <el-table-column prop="monitorUnit" label="单位" align="center" />
                        <el-table-column prop="monitorType" label="监测量类型" align="center" />
                        <el-table-column prop="groupName" label="所属分组" align="center" />
                        <el-table-column label="操作" width="120" align="center">
                            <template #default="{ row }">
                                <el-button size="small" type="danger" @click="handleDeleteMonitor(row)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
                
                <el-tab-pane label="泵组配置" name="pump">
                    <el-form :model="pumpConfigForm" label-width="120px">
                        <el-form-item label="选择泵组">
                            <el-select v-model="pumpConfigForm.pumpGroupId" placeholder="请选择泵组" style="width: 300px">
                                <el-option v-for="item in pumpGroupOptions" :key="item.id" :label="item.pumpGroupName" :value="item.id" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="设备ID">
                            <el-input v-model="pumpConfigForm.pumpDeviceId" placeholder="请输入设备ID" style="width: 300px" />
                        </el-form-item>
                        <el-form-item label="基准值">
                            <el-input-number v-model="pumpConfigForm.baselineValue" :precision="2" style="width: 200px" />
                        </el-form-item>
                        <el-form-item label="基准单位">
                            <el-input v-model="pumpConfigForm.baselineUnit" placeholder="请输入单位" style="width: 200px" />
                        </el-form-item>
                        <el-form-item label="计算方式">
                            <el-select v-model="pumpConfigForm.calcMode" placeholder="请选择计算方式" style="width: 200px">
                                <el-option label="按小时" :value="10" />
                                <el-option label="按日" :value="20" />
                                <el-option label="按月" :value="30" />
                            </el-select>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="savePumpConfig">保存配置</el-button>
                        </el-form-item>
                    </el-form>
                </el-tab-pane>
            </el-tabs>
        </el-dialog>

        <!-- 新增/编辑分组对话框 -->
        <el-dialog v-model="groupDialog.visible" :title="groupDialog.title" width="600px" :close-on-click-modal="false">
            <el-form ref="groupFormRef" :model="groupForm" :rules="groupRules" label-width="100px">
                <el-form-item label="分组名称" prop="groupName">
                    <el-input v-model="groupForm.groupName" placeholder="请输入分组名称" />
                </el-form-item>
                <el-form-item label="分组描述" prop="description">
                    <el-input v-model="groupForm.description" type="textarea" :rows="3" placeholder="请输入分组描述" />
                </el-form-item>
                <el-form-item label="排序号" prop="sortOrder">
                    <el-input-number v-model="groupForm.sortOrder" :min="0" controls-position="right" />
                </el-form-item>
                <el-form-item label="状态" prop="status">
                    <el-radio-group v-model="groupForm.status">
                        <el-radio :label="1">启用</el-radio>
                        <el-radio :label="0">停用</el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="groupDialog.visible = false">取消</el-button>
                <el-button type="primary" @click="submitGroupForm">保存</el-button>
            </template>
        </el-dialog>

        <!-- 新增监测量对话框 -->
        <el-dialog v-model="monitorDialog.visible" title="新增监测量" width="600px" :close-on-click-modal="false">
            <el-form ref="monitorFormRef" :model="monitorForm" :rules="monitorRules" label-width="100px">
                <el-form-item label="选择分组" prop="groupId">
                    <el-select v-model="monitorForm.groupId" placeholder="请选择分组" style="width: 100%">
                        <el-option v-for="item in monitorGroupList" :key="item.id" :label="item.groupName" :value="item.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="选择监测量" prop="monitorId">
                    <el-select v-model="monitorForm.monitorId" placeholder="请选择监测量" style="width: 100%">
                        <el-option v-for="item in monitoringSelectOptions" :key="item.id" :label="item.name" :value="item.id" />
                    </el-select>
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="monitorDialog.visible = false">取消</el-button>
                <el-button type="primary" @click="submitMonitorForm">保存</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import {
    getRegionList,
    getSiteStatusList,
    getFactoryList,
    listSiteInfoAdmin,
    getSiteInfoAdmin,
    addSiteInfoAdmin,
    updateSiteInfoAdmin,
    deleteSiteInfoAdmin,
    getSiteTypeList,
    // 新增接口
    getMonitorGroupList,
    addMonitorGroup,
    updateMonitorGroup,
    getMonitorGroupDetail,
    deleteMonitorGroup,
    getMonitoringList,
    deleteMonitoring,
    getMonitoringSelectList,
    addGroupMonitoring,
    getPumpGroupList,
    getPumpGroupConfig,
    savePumpGroupConfig
} from '@/api/dispatch/affair/distpachSite'

// 查询参数
const queryParams = reactive({
    pageNum: 1,
    pageSize: 10,
    siteName: '',
    siteStatus: '',
    siteId: ''
})

// 表单数据
const form = reactive({
    siteAdminId: undefined,
    siteId: '',
    siteName: '',
    siteCode: '',
    siteType: '',
    regionId: '',
    siteAddress: '',
    latitude: undefined,
    longitude: undefined,
    contactPerson: '',
    contactPhone: '',
    contactEmail: '',
    siteStatus: '1',
    remark: ''
})

// 下拉选项数据
const regionOptions = ref([])
const siteStatusOptions = ref([])
const factoryOptions = ref([])

// 对话框控制
const dialog = reactive({
    visible: false,
    title: ''
})

const detailDialog = reactive({
    visible: false,
    data: {}
})

// 表格数据
const siteList = ref([])
const total = ref(0)
const loading = ref(false)
const selectedRows = ref([])
const formRef = ref()
const siteTypeOptions = ref([])

// 表单验证规则
const rules = reactive({
    siteName: [
        { required: true, message: '请输入站点名称', trigger: 'blur' }
    ],
    siteCode: [
        { required: true, message: '请输入站点编号', trigger: 'blur' }
    ],
    siteId: [
        { required: true, message: '请选择所属水厂', trigger: 'change' }
    ],
    siteStatus: [
        { required: true, message: '请选择站点状态', trigger: 'change' }
    ]
})

// 新增：监测量分组相关数据
const monitorGroupDialog = reactive({
    visible: false,
    title: '监测量分组管理',
    activeTab: 'group',
    currentSite: null
})

const groupDialog = reactive({
    visible: false,
    title: '新增分组'
})

const monitorDialog = reactive({
    visible: false
})

const monitorGroupList = ref([])
const monitoringList = ref([])
const pumpGroupOptions = ref([])
const monitoringSelectOptions = ref([])
const groupLoading = ref(false)
const monitorLoading = ref(false)

const groupForm = reactive({
    id: undefined,
    siteId: '',
    groupName: '',
    description: '',
    sortOrder: 0,
    status: 1
})

const monitorForm = reactive({
    groupId: '',
    monitorId: ''
})

const pumpConfigForm = reactive({
    pumpGroupId: '',
    baselineValue: 0,
    baselineUnit: '',
    calcMode: 10
})

const groupRules = reactive({
    groupName: [
        { required: true, message: '请输入分组名称', trigger: 'blur' }
    ],
    status: [
        { required: true, message: '请选择状态', trigger: 'change' }
    ]
})

const monitorRules = reactive({
    groupId: [
        { required: true, message: '请选择分组', trigger: 'change' }
    ],
    monitorId: [
        { required: true, message: '请选择监测量', trigger: 'change' }
    ]
})

// 获取状态标签
const getStatusLabel = (status) => {
    return status === '1' ? '启用' : '禁用'
}

// 获取名称
const getName = (options, value, valueKey, labelKey) => {
    const item = options.find(item => item[valueKey] === value)
    return item ? item[labelKey] : value
}

// 获取下拉选项数据
const fetchDropdownOptions = async () => {
    try {
        const [regionRes, statusRes, factoryRes, siteTypeRes] = await Promise.all([
            getRegionList(),
            getSiteStatusList(),
            getFactoryList(),
            getSiteTypeList()
        ])
        regionOptions.value = regionRes.data || []
        siteStatusOptions.value = statusRes.data || []
        factoryOptions.value = factoryRes.data || []
        siteTypeOptions.value = siteTypeRes.data || []
    } catch (error) {
        console.error('获取下拉选项失败:', error)
        ElMessage.error('获取下拉选项失败')
    }
}

// 获取站点列表
const fetchSiteList = async () => {
    try {
        loading.value = true
        const res = await listSiteInfoAdmin(queryParams)
        siteList.value = res.rows || []
        total.value = res.total || 0
    } catch (error) {
        console.error('获取站点列表失败:', error)
        ElMessage.error('获取站点列表失败')
    } finally {
        loading.value = false
    }
}

// 获取监测量分组列表
const fetchMonitorGroupList = async () => {
    try {
        groupLoading.value = true
        const res = await getMonitorGroupList(monitorGroupDialog.currentSite?.siteAdminId )
        monitorGroupList.value = res.data || []
    } catch (error) {
        console.error('获取监测量分组列表失败:', error)
        ElMessage.error('获取监测量分组列表失败')
    } finally {
        groupLoading.value = false
    }
}

// 获取监测量列表
const fetchMonitoringList = async () => {
    try {
        monitorLoading.value = true
        const res = await getMonitoringList({ siteId: monitorGroupDialog.currentSite?.siteAdminId })
        monitoringList.value = res.data || []
    } catch (error) {
        console.error('获取监测量列表失败:', error)
        ElMessage.error('获取监测量列表失败')
    } finally {
        monitorLoading.value = false
    }
}

// 获取泵组列表
const fetchPumpGroupList = async () => {
    try {
        console.log(monitorGroupDialog);
        
        const res = await getPumpGroupList(monitorGroupDialog.currentSite?.siteAdminId)
        pumpGroupOptions.value = res.data || []
    } catch (error) {
        console.error('获取泵组列表失败:', error)
        ElMessage.error('获取泵组列表失败')
    }
}

// 获取监测量下拉选项
const fetchMonitoringSelectOptions = async () => {
    try {
        const res = await getMonitoringSelectList(monitorGroupDialog.currentSite?.siteAdminId)
        monitoringSelectOptions.value = res.data || []
    } catch (error) {
        console.error('获取监测量下拉选项失败:', error)
        ElMessage.error('获取监测量下拉选项失败')
    }
}

// 查询按钮
const handleQuery = () => {
    queryParams.pageNum = 1
    fetchSiteList()
}

// 重置查询
const resetQuery = () => {
    queryParams.pageNum = 1
    queryParams.siteName = ''
    queryParams.siteStatus = ''
    queryParams.siteId = ''
    fetchSiteList()
}

// 分页大小变化
const handleSizeChange = (size) => {
    queryParams.pageSize = size
    fetchSiteList()
}

// 当前页码变化
const handleCurrentChange = (page) => {
    queryParams.pageNum = page
    fetchSiteList()
}

// 表格选择变化
const handleSelectionChange = (selection) => {
    selectedRows.value = selection
}

// 新增按钮
const handleAdd = () => {
    dialog.visible = true
    dialog.title = '新增站点'

    // 重置表单
    if (formRef.value) {
        formRef.value.resetFields()
    }

    Object.assign(form, {
        siteAdminId: undefined,
        siteId: '',
        siteName: '',
        siteCode: '',
        siteType: '',
        regionId: '',
        siteAddress: '',
        latitude: undefined,
        longitude: undefined,
        contactPerson: '',
        contactPhone: '',
        contactEmail: '',
        siteStatus: '1',
        remark: ''
    })
}

// 编辑按钮
const handleEdit = async (row) => {
    try {
        const res = await getSiteInfoAdmin(row.siteAdminId)
        Object.assign(form, {
            siteAdminId: res.data.siteAdminId,
            siteId: res.data.siteId,
            siteName: res.data.siteName,
            siteCode: res.data.siteCode,
            siteType: res.data.siteType,
            regionId: res.data.regionId,
            siteAddress: res.data.siteAddress,
            latitude: res.data.latitude,
            longitude: res.data.longitude,
            contactPerson: res.data.contactPerson,
            contactPhone: res.data.contactPhone,
            contactEmail: res.data.contactEmail,
            siteStatus: res.data.siteStatus,
            remark: res.data.remark
        })

        dialog.visible = true
        dialog.title = '编辑站点'
    } catch (error) {
        console.error('获取站点详情失败:', error)
        ElMessage.error('获取站点详情失败')
    }
}

// 查看详情
const handleView = async (row) => {
    try {
        const res = await getSiteInfoAdmin(row.siteAdminId)
        detailDialog.data = res.data
        detailDialog.visible = true
    } catch (error) {
        console.error('获取站点详情失败:', error)
        ElMessage.error('获取站点详情失败')
    }
}

// 删除按钮
const handleDelete = (row) => {
    ElMessageBox.confirm(`确认删除站点 "${row.siteName}" 吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        return deleteSiteInfoAdmin([row.siteAdminId])
    }).then(() => {
        ElMessage.success('删除成功')
        fetchSiteList()
    }).catch(() => { })
}

// 提交表单
const submitForm = async () => {
    try {
        await formRef.value.validate()

        if (form.siteAdminId) {
            await updateSiteInfoAdmin(form)
        } else {
            await addSiteInfoAdmin(form)
        }

        ElMessage.success('操作成功')
        dialog.visible = false
        fetchSiteList()
    } catch (error) {
        console.error('保存站点信息失败:', error)
    }
}

// 显示监测量分组对话框
const showMonitorGroupDialog = (row) => {
    monitorGroupDialog.visible = true
    monitorGroupDialog.currentSite = row || null
    monitorGroupDialog.title = row ? `监测量分组管理 - ${row.siteName}` : '监测量分组管理'
    
    fetchMonitorGroupList()
    if (row) {
        fetchMonitoringList()
        fetchPumpGroupList()
    }
}

// 新增分组
const handleAddGroup = () => {
    groupDialog.visible = true
    groupDialog.title = '新增分组'
    Object.assign(groupForm, {
        id: undefined,
        siteId: monitorGroupDialog.currentSite?.siteAdminId || '',
        groupName: '',
        description: '',
        sortOrder: 0,
        status: 1
    })
}

// 编辑分组
const handleEditGroup = async (row) => {
    try {
        const res = await getMonitorGroupDetail(row.id)
        Object.assign(groupForm, res.data)
        groupDialog.visible = true
        groupDialog.title = '编辑分组'
    } catch (error) {
        console.error('获取分组详情失败:', error)
        ElMessage.error('获取分组详情失败')
    }
}

// 删除分组
const handleDeleteGroup = (row) => {
    ElMessageBox.confirm(`确认删除分组 "${row.groupName}" 吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        return deleteMonitorGroup(row.id)
    }).then(() => {
        ElMessage.success('删除成功')
        fetchMonitorGroupList()
    }).catch(() => { })
}

// 新增监测量
const handleAddMonitor = async () => {
    await fetchMonitoringSelectOptions()
    monitorDialog.visible = true
    Object.assign(monitorForm, {
        groupId: '',
        monitorId: ''
    })
}

// 删除监测量
const handleDeleteMonitor = (row) => {
    ElMessageBox.confirm(`确认删除监测量 "${row.monitorName}" 吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        return deleteMonitoring(row.monitorId)
    }).then(() => {
        ElMessage.success('删除成功')
        fetchMonitoringList()
    }).catch(() => { })
}

// 提交分组表单
const submitGroupForm = async () => {
    try {
        if (groupForm.id) {
            await updateMonitorGroup(groupForm)
        } else {
            await addMonitorGroup(groupForm)
        }
        ElMessage.success('操作成功')
        groupDialog.visible = false
        fetchMonitorGroupList()
    } catch (error) {
        console.error('保存分组失败:', error)
    }
}

// 提交监测量表单
const submitMonitorForm = async () => {
    try {
        await addGroupMonitoring(monitorForm)
        ElMessage.success('操作成功')
        monitorDialog.visible = false
        fetchMonitoringList()
    } catch (error) {
        console.error('新增监测量失败:', error)
    }
}

// 保存泵组配置
const savePumpConfig = async () => {
    try {
        await savePumpGroupConfig({ ...pumpConfigForm , siteId: monitorGroupDialog.currentSite?.siteAdminId })
        ElMessage.success('保存成功')
    } catch (error) {
        console.error('保存泵组配置失败:', error)
        ElMessage.error('保存泵组配置失败')
    }
}

// 初始化加载数据
onMounted(() => {
    fetchDropdownOptions()
    fetchSiteList()
})
</script>

<style scoped>
</style>